﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.StorageHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;
using WeiboSdk;
using WeiboSdk.PageViews;

namespace ComicIsland.App.Controls
{
    public partial class OAuthControl : UserControl
    {
        public event EventHandler OnClose;

        public OAuthControl()
        {
            InitializeComponent();
        }





        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.OnClose != null)
            {
                this.OnClose(sender, e);
            }
        }


        #region ******************************第三方登录******************************
        #region ********************新浪微博登录********************
        private void SinaStackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            // 此处使用自己 AppKey 和 AppSecret，未经审核的应用只支持用申请该Appkey的帐号来获取数据
            SdkData.AppKey = App.SinaWeibo_AppKey;
            SdkData.AppSecret = App.SinaWeibo_AppSecret;
            SdkData.RedirectUri = App.SinaWeibo_RedirectUri;
            GetSinaWeiboLogin();
        }

        void GetSinaWeiboLogin()
        {
            UserThirdLoginInfo userInfo = new UserThirdLoginInfo();
            userInfo.InsertDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            userInfo.ThirdPlatform = (int)Helper.ThirdPlatform.SinaWeibo;

            if (string.IsNullOrEmpty(SdkData.AppKey) || string.IsNullOrEmpty(SdkData.AppSecret) || string.IsNullOrEmpty(SdkData.RedirectUri))
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("请联系管理员设置appkey值！");
                });
                return;
            }
            //AuthenticationView.OAuth2VerifyCompleted = (e1, e2, e3) => VerifyBack(e1, e2, e3);
            //AuthenticationView.OBrowserCancelled+=         
            //其它通知事件...
            AuthenticationView.OAuth2VerifyCompleted += delegate(bool isSucess, SdkAuthError errCode, SdkAuth2Res response)
            {
                if (errCode.errCode == SdkErrCode.SUCCESS)
                {
                    if (null != response)
                    {
                        userInfo.AccessToken = response.accesssToken;
                        //userInfo.RefleshToken = response.refleshToken;
                        userInfo.ExpriesIn = response.expriesIn;
                        userInfo.UserId = response.UserId;
                        if (string.IsNullOrWhiteSpace(userInfo.AccessToken) || string.IsNullOrWhiteSpace(userInfo.UserId) || string.IsNullOrWhiteSpace(userInfo.ExpriesIn))
                        {
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                MessageToastManager.Show("登录失败，请重试！", MessageToastLevel.Error);
                                if ((Application.Current.RootVisual as PhoneApplicationFrame).CanGoBack)
                                {
                                    (Application.Current.RootVisual as PhoneApplicationFrame).GoBack();
                                }
                            });
                        }
                        else
                        {
                            GetSinaWeiboUserInfo(userInfo);
                        }
                    }
                }
                else if (errCode.errCode == SdkErrCode.NET_UNUSUAL)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("检查网络");
                    });
                }
                else if (errCode.errCode == SdkErrCode.SERVER_ERR)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("服务器返回错误，错误代码:" + errCode.specificCode);
                    });
                }
            };

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    Uri uri = new Uri("/WeiboSdk;component/PageViews/AuthenticationView.xaml", UriKind.Relative);
                    (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(uri);
                }
                catch { }
            });
        }

        void GetSinaWeiboUserInfo(UserThirdLoginInfo userInfo)
        {
            cmdGetUserInfo data = new cmdGetUserInfo()
            {
                acessToken = userInfo.AccessToken,
                uid = userInfo.UserId
            };
            SdkNetEngine net = new SdkNetEngine();
            net.RequestCmd(SdkRequestType.GET_USERINFO, data, (e1, e2) =>
            {
                if (e2.errCode == SdkErrCode.SUCCESS)
                {
                    string result = e2.content;
                    LogHelper.LogInfo(result);
                    JObject jo = JObject.Parse(result);
                    try
                    {
                        //{"id":1872997893,"idstr":"1872997893","class":1,"screen_name":"国学经典食疗养生楚才书店","name":"国学经典食疗养生楚才书店","province":"11","city":"5","location":"北京 朝阳区","description":"楚才书店竭诚为您提供专业的国学经典、职场励志成功学、心理营销学、养生食疗、妇婴幼儿、家庭教育、考试专用书服务！","url":"http://shop65062777.taobao.com/","profile_image_url":"http://tp2.sinaimg.cn/1872997893/50/40019484811/1","profile_url":"blackcore","domain":"blackcore","weihao":"","gender":"m","followers_count":428,"friends_count":413,"pagefriends_count":0,"statuses_count":1281,"favourites_count":1,"created_at":"Wed Nov 24 14:33:33 +0800 2010","following":false,"allow_all_act_msg":false,"geo_enabled":true,"verified":false,"verified_type":200,"remark":"","status":{"created_at":"Wed Oct 22 18:55:22 +0800 2014","id":3768548000394335,"mid":"3768548000394335","idstr":"3768548000394335","text":"赞http://t.cn/R75n0JH","source_type":1,"source":"<a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>","favorited":false,"truncated":false,"in_reply_to_status_id":"","in_reply_to_user_id":"","in_reply_to_screen_name":"","pic_urls":[],"geo":null,"reposts_count":0,"comments_count":0,"attitudes_count":0,"mlevel":0,"visible":{"type":0,"list_id":0},"darwin_tags":[]},"ptype":0,"allow_all_comment":true,"avatar_large":"http://tp2.sinaimg.cn/1872997893/180/40019484811/1","avatar_hd":"http://tp2.sinaimg.cn/1872997893/180/40019484811/1","verified_reason":"","verified_trade":"","verified_reason_url":"","verified_source":"","verified_source_url":"","follow_me":false,"online_status":0,"bi_followers_count":138,"lang":"zh-cn","star":0,"mbtype":0,"mbrank":0,"block_word":0,"block_app":0,"credit_score":80,"urank":0}                        
                        JToken screen_name = jo["screen_name"];
                        JToken gender = jo["gender"];
                        JToken profile_image_url = jo["profile_image_url"];
                        userInfo.DetailInfo = result;
                        userInfo.ScreenName = screen_name.ToString();
                        if (!string.IsNullOrWhiteSpace(gender.ToString()) && gender.ToString().ToLower().Equals("m"))
                            userInfo.Gender = ((int)Helper.UserGender.Male).ToString();
                        else
                            userInfo.Gender = ((int)ComicIsland.Common.Helper.UserGender.Female).ToString();
                        userInfo.ProfileImageUrl = profile_image_url.ToString();

                        if (string.IsNullOrWhiteSpace(userInfo.AccessToken) || string.IsNullOrWhiteSpace(userInfo.UserId)
                       || string.IsNullOrWhiteSpace(userInfo.ExpriesIn) || string.IsNullOrWhiteSpace(userInfo.ScreenName) || string.IsNullOrWhiteSpace(userInfo.ProfileImageUrl))
                        {
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                MessageToastManager.Show("登录失败，请重试！", MessageToastLevel.Error);
                                if ((Application.Current.RootVisual as PhoneApplicationFrame).CanGoBack)
                                {
                                    (Application.Current.RootVisual as PhoneApplicationFrame).GoBack();
                                }
                            });
                        }
                        else
                        {
                            QQAuthenticationPage.Login(userInfo);
                        }
                    }
                    catch (Exception err)
                    {
                        LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    }
                }
                else if (e2.errCode == SdkErrCode.NET_UNUSUAL)
                {
                    MessageBox.Show("网络连接错误！");
                }
                else if (e2.errCode == SdkErrCode.SERVER_ERR)
                {
                    MessageBox.Show("服务器返回错误，错误码:" + e2.specificCode);
                }
            });
        }
        #endregion  ********************新浪微博登录********************

        #region  ********************QQ登录********************
        private void QQStackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                Uri uri = new Uri("/Controls/QQAuthenticationPage.xaml", UriKind.Relative);
                (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(uri);
            }
            catch { }

        }
        #endregion  ********************QQ登录********************
        #endregion ******************************第三方登录******************************


    }
}
